package cn.com.apple.controller;

import cn.com.apple.mapper.OrderMapper;
import cn.com.apple.pojo.Order;
import cn.com.apple.pojo.ProductBuyPair;
import cn.com.apple.service.ProductService;
import cn.com.dcsgo.api.client.ItemClient;
import cn.com.dcsgo.api.dto.ItemDTO;
import cn.com.dcsgo.api.dto.OrderDetailDTO;
import cn.com.dcsgo.aspect.ApiOperationLog;
import cn.com.dcsgo.utils.ResponseResult;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.lang.Snowflake;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

@RestController
@RequestMapping("order")
@Api(value = "OrderController",tags = "订单接口")
public class OrderController {

    @Autowired
    private final OrderMapper orderMapper;

    @Autowired
    ProductService productService;

    private final Snowflake snowflake = new Snowflake();

    public OrderController(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }

    @GetMapping("getOrderById")
    @ApiOperationLog(description = "通过id查询订单信息")
    @Operation(summary = "通过id查询", description = "通过订单编号查询订单信息")
    public ResponseResult<Order> findOne(@RequestParam int id) {
        Order order = orderMapper.selectById(id);
        return ResponseResult.success(order);
    }

    /**
     * 创建订单
     * @param params 包含订单信息的参数Map，包括user_id, product_paris{"1001":1,"1002":5,"1003":4}, shopping_address等
     * @return String通知是否创建成功
     */
    @PostMapping("createOrder")
    @SentinelResource(value = "createOrder", blockHandler = "createOrderBlockHandler")
    @Operation(summary = "创建订单", description = "根据传递的body来创建订单")
    public ResponseResult<String> createOrder(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("user_id") || !params.containsKey("product_paris") ||
                !params.containsKey("shopping_address")) {
            return ResponseResult.fail("缺少必要参数!");
        }

        Order order = new Order();

        try {
            order.setUser_id(Long.parseLong(params.get("user_id").toString()));

            Map<String,Integer> buyProductItemPair = (Map<String, Integer>) params.get("product_paris");
            List<ProductBuyPair>product_pairs = new ArrayList<>();
            List<Long>item_ids = new ArrayList<>();
            for(Map.Entry<String,Integer> pair:buyProductItemPair.entrySet()){
                product_pairs.add(new ProductBuyPair(pair.getKey(),pair.getValue()));
                item_ids.add(Long.parseLong(pair.getKey()));
            }
            List<ItemDTO> productItemDTOS = productService.queryItemsByIds(item_ids);


            List<OrderDetailDTO> orderDetailDTOS = new ArrayList<>();
            float total_amount = 0;

            for(ItemDTO item:productItemDTOS){
                Integer buyNum = buyProductItemPair.get(String.valueOf(item.getId()));
                if(item.getStock() < buyNum){
                    return ResponseResult.fail(String.format("%s库存不足,余量:%d",item.getName(),item.getStock()));
                }
                item.setStock(item.getStock() - buyNum);
                orderDetailDTOS.add(new OrderDetailDTO().setItemId(item.getId()).setNum(buyNum));
                total_amount += item.getPrice() * buyNum;
            }

            order.setOrder_id(snowflake.nextId());
            order.setProduct_pairs(product_pairs);
            order.setTotal_amount(total_amount);
            order.setOrder_status("待发货");
            order.setCreate_datetime(LocalDateTime.now());
            order.setUpdate_datetime(LocalDateTime.now());
            order.setShopping_address(params.get("shopping_address").toString());

            int result = orderMapper.insert(order);
            if (result != 0) {
                productService.deductStock(orderDetailDTOS);
                return ResponseResult.success("订单创建成功!");
            }
            return ResponseResult.fail("订单创建失败!");

        } catch (NumberFormatException e) {
            orderMapper.deleteById(order);
            return ResponseResult.fail("参数格式错误: " + e.getMessage());
        } catch (Exception e) {
            orderMapper.deleteById(order);
            return ResponseResult.fail("订单创建失败: " + e.getMessage());
        }
    }

    public ResponseResult<String> createOrderBlockHandler(BlockException e){
        return ResponseResult.fail("创建订单太过于频繁");
    }


    /**
     * 删除指定订单
     * @param id 订单
     * @return String通知是否删除成功
     */
    @DeleteMapping("deleteOrderById")
    @ApiOperationLog(description = "删除订单")
    @Operation(summary = "删除订单", description = "根据订单编号删除订单信息")
    public ResponseResult<String> deleteOrder(@RequestParam Long id) {
        int result = orderMapper.deleteById(id);
        if (result > 0) {
            return ResponseResult.success("订单删除成功！");
        } else {
            return ResponseResult.fail("订单删除失败，订单不存在或已被删除！");
        }
    }

    /**
     * 获取用户订单列表
     *
     * @param userId 用户ID
     * @param status 订单状态（可选：已取消, 待发货, 发货中, 已发货, 已完成）
     * @return 指定用户所有的订单数据
     */
    @GetMapping("getUserOrders")
    @ApiOperationLog(description = "查询用户订单列表")
    @Operation(
            summary = "获取用户订单",
            description = "根据用户ID查询订单列表"
    )
    public ResponseResult<List<Order>> getUserOrders(@RequestParam Long userId, @RequestParam(required = false) String status) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        if(status != null && !status.isEmpty()) {
            queryWrapper.eq("order_status", status);
        }
        List<Order> orders = orderMapper.selectList(queryWrapper);
        return ResponseResult.success(orders);
    }

    /**
     * 删除指定用户的所有订单
     * @param userId 用户ID
     * @return String通知是否删除成功
     */
    @DeleteMapping("deleteUserOrders")
    @ApiOperationLog(description = "删除用户所有订单")
    @Operation(
            summary = "删除用户所有订单",
            description = "根据用户ID删除该用户的所有订单信息"
    )
    public ResponseResult<String> deleteUserOrders(@RequestParam Long userId) {
        try {
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);

            int result = orderMapper.delete(queryWrapper);

            if (result > 0) {
                return ResponseResult.success("成功删除 " + result + " 个订单！");
            } else {
                return ResponseResult.success("该用户没有订单可删除！");
            }
        } catch (Exception e) {
            return ResponseResult.fail("删除用户订单失败: " + e.getMessage());
        }
    }


    /**
     * 更新订单状态
     *
     * @param id      订单编号（必填）
     * @param status  新状态（必填，允许值：已取消/待发货/发货中/已发货/已完成）
     * @return        操作结果
     */
    @PutMapping("updateOrderStatus")
    @ApiOperationLog(description = "更新订单状态")
    @Operation(
            summary = "更新订单状态",
            description = "根据订单编号修改订单状态，支持的状态值为：已取消、待发货、发货中、已发货、已完成"
    )
    public ResponseResult<String> updateOrderStatus(@RequestParam Long id, @RequestParam String status) {

        // 验证状态有效性
        if (!Order.isValidStatus(status)) {
            return ResponseResult.fail("无效的订单状态！");
        }

        // 查询订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return ResponseResult.fail("订单不存在！");
        }

        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id", id).set("order_status", status);

        int result = orderMapper.update(order, updateWrapper);
        if (result > 0) {
            return ResponseResult.success("订单状态更新成功！");
        } else {
            return ResponseResult.fail("订单状态更新失败！");
        }
    }


    @PutMapping("updateOrderShoppingAddress")
    @ApiOperationLog(description = "更新订单收获地址")
    @Operation(
            summary = "更新订单收获地址",
            description = "根据订单编号修改订单收获地址"
    )
    public ResponseResult<String> updateOrderShoppingAddress(@RequestParam Long id, @RequestParam String address){

        // 检查订单是否存在
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return ResponseResult.fail("订单不存在!");
        }


        order.setShopping_address(address);
        order.setUpdate_datetime(LocalDateTime.now());

        int result = orderMapper.updateById(order);
        if (result != 0) {
            return ResponseResult.success("订单商品信息更新成功!");
        }

        return ResponseResult.fail("订单商品信息更新失败!");
    }


    @PutMapping("cancelOrder")
    @ApiOperationLog(description = "取消订单")
    @Operation(
            summary = "取消订单",
            description = "根据订单编号取消订单,并且把订单的商品数据回滚到数据库"
    )
    public ResponseResult<String> cancelOrder(@RequestParam Long id){
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return ResponseResult.fail("订单不存在!");
        }

        if(order.getOrder_status().equals("已取消")){
            return ResponseResult.fail("订单已经被取消过!");
        }

        List<OrderDetailDTO> orderDetailDTOS = order.getProduct_pairs()
                .stream()
                .map(p -> new OrderDetailDTO().setItemId(Long.parseLong(p.getId())).setNum(p.getQuantity())).toList();

        productService.addStock(orderDetailDTOS);

        order.setOrder_status("已取消");
        order.setUpdate_datetime(LocalDateTime.now());
        int res = orderMapper.updateById(order);
        if(res <= 0) {
            return ResponseResult.fail("取消失败!");
        }
        return ResponseResult.success("取消成功!");
    }

}
